<?php
/**
 * 定义 Controller_BoIndex 类
 *
 * @copyright Copyright (c) 2009 iTeam
 * @author sunnycoolboy
 * @package leadtone
 * @version BoIndex 2009-04-02
 */

// {{{ includes
FLEA::loadClass('Controller_BoUploadImg');
// }}}

class Controller_BoIndex extends Controller_BoUploadImg
{
	/**
     * 操作产品分类的对象
     *
     * @var Model_ArticleClasses
     */
    var $_modelClasses;
    

    /**
     * @var Model_Articles
     */
    var $_modelArticles;
    
    
    /**
     * @var access
     */
    var $access;
    
    /**
     * @var catid   类别ID  首页轮播图类别ID为20
     */
    var $imgCatId;
    var $oimgCatId;
    var $dbo;
	
	/**
     * 构造函数
     *
     * @return Controller_BoIndex
     */
    function Controller_BoIndex() {
        parent::Controller_BoUploadImg();
        $this->access = FRONGPAGE_ADMIN;
        $this->imgCatId = INDEX_IMG_CLASS;
        $this->oimgCatId = OTHER_IMG_CLASS;
        //用户角色权限控制
        if(!$this->checkDispatcher($this->access)){
            redirect(url('BoDashboard','ErrorIn'));
        }        
        $this->_modelClasses =& FLEA::getSingleton('Model_Categories');
        $this->_modelArticles =& FLEA::getSingleton('Model_Articles');
        $this->dbo = &FLEA::getDBO();
    }
    
    /**
     * 显示首页轮播图列表
     */
    function actionIndex() {
    	$catid = $this->imgCatId;
        $field = array('class_id' => $catid);        
        $table =& $this->_modelArticles->getTable();
        $pk = $table->primaryKey;
        $rowset = $table->findAll($field, 'hot DESC,dateline DESC', 4);
//        dump($this->dbo->log);
        $this->_setBack();
        $listTitle = "首页轮播图片";
        $listSrc = LEADTONE_DIR."/index.php?controller=Default&action=Index";
        include(TPL_DIR . '/BoImgsList.php');
    }
	function actionProList() {
    	$catid = $this->oimgCatId;
        $field = array('class_id' => $catid);        
        $table =& $this->_modelArticles->getTable();
        $pk = $table->primaryKey;
        $rowset = $table->findAll($field, 'hot DESC,dateline DESC', 4);
//        dump($this->dbo->log);
        $this->_setBack();
        $listTitle = "其他页轮播图片";
        $listSrc = LEADTONE_DIR."/index.php?controller=Default&action=ProList";
        include(TPL_DIR . '/BoImgsList.php');
    }
    
    /**
     * 显示产品的图片管理器
     */
    function actionPicman($errorMessage = null) {
    	$catid = $_GET['catid']?$_GET['catid']:$this->imgCatId;
    	$table =& $this->_modelArticles->getTable();
        $pk = $table->primaryKey;
    	$article = $this->_modelArticles->getArticle($_GET['id']);
    	switch ($catid){
    		case $this->imgCatId:
    			$title = "发布轮播图";
    			$ispic = true;
    		case $this->oimgCatId:
    			$title = "发布其他页轮播图";
    			$ispic = true;
    			break;
    		default:
    			$title = "发布轮播图";
    			$ispic = true;
    	}
        include(TPL_DIR . '/BoImgEdit.php');
    }
    
    /**
     * 上传缩略图
     */
    function actionUploadPhoto($errorMessage = null) {
    	$catid = $_GET['catid']?$_GET['catid']:$this->imgCatId;
    	__TRY();
        $user = $this->getUser();
		if(!$_POST['article_id'])$_POST['dateline'] = time(); 
		else $_POST['updated'] = time(); 
		$_POST['author'] = $user['ID'];
		$_POST['class_id'] = $catid;
		$_POST['title'] = $this->stripHtml($_POST['title']);//添加去除html和script标记的轮播名称
		$_POST['content'] = $this->stripHtml($_POST['spaw1']);//添加去除html和script标记的轮播链接
        $errorMessage = $this->_uploadPicture();
        if(!$errorMessage == "" && is_array($errorMessage))$_POST['image_src'] = $errorMessage['filename'];//上传图片
        else unset($_POST['image_src']);
        $this->_modelArticles->saveArticle($_POST);
        $ex = __CATCH();
        if (__IS_EXCEPTION($ex)) {
            //return $this->Picman($_POST, $ex->getMessage());
            var_dump($ex->getMessage());
            exit;
        }
        switch ($catid){
        	case $this->imgCatId:
        		redirect($this->_url('Index'));
        		break;
        	case $this->oimgCatId:
        		redirect($this->_url('ProList'));
        		break;        	
        	default:
        		redirect($this->_url('Index'));
        }
    }
    
	/**
     * 处理图片上传
     */
    function _uploadPicture() {

            $uploader =& FLEA::getSingleton('FLEA_Helper_FileUploader');
            /* @var $uploader FLEA_Helper_FileUploader */

            $errorMessage = "";
            // 检查上传文件是否存在
			if ($uploader->isFileExist('postfile')) {
	            // 检查文件扩展名是否是允许上传的类型
	            $file =& $uploader->getFile('postfile');
	            if (!$file->check(FLEA::getAppInf('photoFileExts'))) {
	                $errorMessage =_T('ui_p_invalid_filetype');
	                break;
	            }
	
	            // 上传图片
	            __TRY();
	            $filetype = $file->getExt();//获取图片后缀
	            $filename = $this->uploadPhoto($file,$filetype);
	            $ex = __CATCH();
	            if (__IS_EXCEPTION($ex)) {
	                $errorMessage = $ex->getMessage();
	                break;
	            }else $errorMessage['filename'] = $filename;
			}
			
            if($errorMessage!= "" && !is_array($errorMessage)){
				echo "<script>alert('".$errorMessage."');";
				echo "history.back();</script>";
				exit;
			}
		
        /*$src = FLEA::getAppInf('uploadDir') . DS . $filename;
        $img = UPLOAD_DIR. "/" .$filename;
        include(TPL_DIR . '/BoPagePicman.php');*/
        return $errorMessage;
    }
    
    /**
     * 添加图片
     *
     * @param
     * @param FLEA_Helper_UploadFile $file
     *
     * @return boolean
     */
    function uploadPhoto(&$file,$type) {
        $filename = 'guoguo' . time() . '.' . $type;        
        $file->move(FLEA::getAppInf('uploadDir') . DS . $filename);
        return $filename;
    }
    
    function actionRemove() {
        $this->_modelArticles->removeArticle($_GET['id']);
        $this->_goBack();
    }
    function actionUpdateImg(){
		$catid = $this->imgCatId;
        $field = array('class_id' => $catid);
        $table =& $this->_modelArticles->getTable();
        $pk = $table->primaryKey;
        $rowset = $table->findAll($field, 'hot DESC,dateline DESC',4);
        $content = '<?xml version="1.0" encoding="UTF-8"?>
<setting>
  <normal width="940" height="300" showType="2" tweenTime="30"/>
  <autoPlay isOn="false" timeout="5"/>
  <previewMenu isOn="false" menuType="left" menuX="10" menuY="40" previewWidth="150" previewHeight="50" previewDis="30" bgColor="0xCCCCCC" onSelectColor="0x333333" border="3" loadingColor="0x333333" loadingColor2="0x333333"/>
  <normalMenu isOn="true" menuDis="25" btnColor="0xCCCCCC" onSelectColor="0x333333" loadingColor="0x333333"/>
  <point isOn="false" btnColor="0xCCCCCC" onSelectColor="0x333333"/>
  <dataList>';
    	foreach ($rowset as $qrow){
	    	$content.='
	<data img="Upload/'.$qrow['image_src'].'" timeout="8000"/>';
	    }
	    $content.='
  </dataList>
</setting>';
	    $result = $this->saveFile(FLASH_DIR.'/index.xml',$content);
	    if($result)echo "更新成功";
	    else echo "更新失败";
    }
	function actionUpdateoImg(){
		$catid = $this->oimgCatId;
        $field = array('class_id' => $catid);
        $table =& $this->_modelArticles->getTable();
        $pk = $table->primaryKey;
        $rowset = $table->findAll($field, 'hot DESC,dateline DESC',4);
        $content = '<?xml version="1.0" encoding="UTF-8"?>
<setting>
  <normal width="940" height="200" showType="2" tweenTime="30"/>
  <autoPlay isOn="false" timeout="5"/>
  <previewMenu isOn="false" menuType="left" menuX="10" menuY="40" previewWidth="150" previewHeight="50" previewDis="30" bgColor="0xCCCCCC" onSelectColor="0x333333" border="3" loadingColor="0x333333" loadingColor2="0x333333"/>
  <normalMenu isOn="true" menuDis="25" btnColor="0xCCCCCC" onSelectColor="0x333333" loadingColor="0x333333"/>
  <point isOn="false" btnColor="0xCCCCCC" onSelectColor="0x333333"/>
  <dataList>';
    	foreach ($rowset as $qrow){
	    	$content.='
	<data img="Upload/'.$qrow['image_src'].'" timeout="8000"/>';
	    }
	    $content.='
  </dataList>
</setting>';
	    $result = $this->saveFile(FLASH_DIR.'/other.xml',$content);
	    if($result)echo "更新成功";
	    else echo "更新失败";
    }
    //文件操作
	protected function saveFile($filename,$content){
    	$file_contents = $content;
		// 首先我们要确定文件存在并且可写。		
		if (is_writable($filename)) {			
			$result = $this->Dofile($filename,$file_contents);
			if($result) return true;
			else return false;
		} else {
			$error = $filename . "无法读取或不可写！";
			return false;
		}
    }
    //文件操作
	protected function Dofile($filename,$file_contents){
		if (!$handle = fopen($filename, 'w')) {
			return "操作" . $filename . "失败";
			exit;
		}
		// 将$file_contents写入到我们打开的文件中。
		if (fwrite($handle, $file_contents) === FALSE) {
			return "can not write into $filename";
			return "操作" . $filename . "失败";
			exit;
		}		
		fclose($handle);		
		return true;		
    }
}